import RongRTC from '@rongcloud/im/RongRTC-wechat-minip-3.2.4.js'
import RongCallLib from '@rongcloud/im/RongCallLib-wechat-minip-3.2.4.js'
import ObserverList from './observer.js'

const videoWatcher = new ObserverList();
const commandWatcher = new ObserverList();

export default function(RongIMLib) {

	let rongCallLib = RongCallLib.init({
		timeout: 20000,
		RongIMLib,
		RongRTC,
	});

	const watchVideo = (watcher) => {
		videoWatcher.add(watcher, true);
	};

	const watchCommand = (watcher) => {
		commandWatcher.add(watcher);
	};

	const destroy = () => {
		videoWatcher.remove();
		commandWatcher.remove();
		rongCallLib.destroy();
	}

	rongCallLib.videoWatch(function(result) {
		videoWatcher.notify(result);
	});

	rongCallLib.commandWatch(function(message) {
		commandWatcher.notify(message);
	});

	const call = (targetId) => {
		return new Promise((resolve, reject) => {
			rongCallLib.call({
				conversationType: RongIMLib.CONVERSATION_TYPE.PRIVATE,
				targetId,
				mediaType: RongCallLib.VoIPMediaType.MEDIA_VIDEO,
			}, (error) => {
				error ? reject(error) : resolve();
			});
		})
	};

	const accept = (targetId) => {
		return new Promise((resolve, reject) => {
			rongCallLib.accept({
				conversationType: RongIMLib.CONVERSATION_TYPE.PRIVATE,
				targetId,
				mediaType: RongCallLib.VoIPMediaType.MEDIA_VIDEO,
			}, function(error) {
				error ? reject(error) : resolve();
			});
		})
	};

	const hungup = (targetId) => {
		return new Promise((resolve, reject) => {
			rongCallLib.hungup({
				conversationType: RongIMLib.CONVERSATION_TYPE.PRIVATE,
				targetId
			}, function(error) {
				error ? reject(error) : resolve();
			});
		})
	};


	const reject = (targetId) => {
		console.log('拒绝通话');
		return new Promise((resolve, reject) => {
			rongCallLib.reject({
				conversationType: RongIMLib.CONVERSATION_TYPE.PRIVATE,
				targetId
			}, function(error) {
				console.log('拒绝通话失败', error);
				error ? reject(error) : resolve();
			});
		})
	};


	return {
		call,
		accept,
		hungup,
		reject,
		watchVideo,
		watchCommand,
		destroy,
		MessageType: RongCallLib.MessageType
	};
};
